#!/bin/sh
# 把全程日志同时打到串口（/dev/ttyS2 是 RK3568 调试串口，板子不同可换 /dev/ttyS0）
LOG_TTY=/dev/ttyS2

# ---------- 读原始 POST ----------
read -r POST_STRING
# 写原始数据到串口
printf "【LED-CGI】收到原始POST: %s\\r\\n" "$POST_STRING" > $LOG_TTY

# ---------- 简易解析 ----------
STATUS=$(printf '%s' "$POST_STRING"   | sed -n 's/.*status=\([^&]*\).*/\1/p')
BRIGHTNESS=$(printf '%s' "$POST_STRING" | sed -n 's/.*brightness=\([^&]*\).*/\1/p')

case "$STATUS" in
  true|on|1) LED=1 ;;
  *)         LED=0 ;;
esac

# ---------- 控制台日志 ----------
printf "【LED-CGI】解析结果: LED=%s  brightness=%s\\r\\n" "$LED" "$BRIGHTNESS" > $LOG_TTY

# ---------- 硬件控制（示例） ----------
if [ "$LED" = "1" ]; then
  # echo "$BRIGHTNESS" > /sys/class/leds/led0/brightness
  :
else
  # echo 0 > /sys/class/leds/led0/brightness
  :
fi

# ---------- 组装 JSON 回包 ----------
JSON_OUT="{\"result\":\"ok\",\"led\":$LED,\"brightness\":$BRIGHTNESS}"
printf "【LED-CGI】返回JSON: %s\\r\\n" "$JSON_OUT" > $LOG_TTY

# ---------- 正式回 HTTP ----------
echo "Content-type: application/json"
echo ""
printf '%s\n' "$JSON_OUT"